class_name BattleHandler
extends Node

# ===============================================

signal player_won
signal enemy_won

# ===============================================

@export var game_state: GameState
@export var game_area: PLayArea
@export var game_area_unit_grid: UnitGrid
@export var battle_unit_grid: UnitGrid

# ===============================================

@onready var scene_spawner: SceneSpawner = $SceneSpawner

const ZOMBIE = preload("res://data/enemies/zombie.tres")

const ZOMBIE_TEST_POSITIONS := [
	Vector2i(8, 1),
	Vector2i(7, 4),
	Vector2i(8, 3),
	Vector2i(9, 5),
	Vector2i(9, 6),
]

# ===============================================

func __setup_battle_unit(coord: Vector2i, new_unit: BattleUnit) -> void:
	new_unit.global_position = game_area.get_global_from_tile(coord) + Vector2(0, -Arena.QUARTER_CELL_SIZE.y)
	new_unit.tree_exited.connect(__on_battle_unit_died)
	battle_unit_grid.add_unit(coord, new_unit)


func __prepare_fight() -> void:
	get_tree().call_group("units", "hide")
	for coord: Vector2i in game_area_unit_grid.get_all_occupied_tiles():
		var unit: Unit = game_area_unit_grid.units[coord]
		var new_unit: BattleUnit = scene_spawner.spawn_scene(battle_unit_grid) as BattleUnit
		new_unit.add_to_group("player_units")
		new_unit.stats = unit.stats
		new_unit.stats.team = UnitStats.Team.PLAYER
		__setup_battle_unit(coord, new_unit)
	for coord: Vector2i in ZOMBIE_TEST_POSITIONS:
		var new_unit: BattleUnit = scene_spawner.spawn_scene(battle_unit_grid) as BattleUnit
		new_unit.add_to_group("enemy_units")
		new_unit.stats = ZOMBIE
		new_unit.stats.team = UnitStats.Team.ENEMY
		__setup_battle_unit(coord, new_unit)


func __clean_up_fight() -> void:
	get_tree().call_group("player_units", "queue_free")
	get_tree().call_group("enemy_units", "queue_free")
	get_tree().call_group("units", "show")


func __on_battle_unit_died() -> void:
	if not get_tree() or not game_state.is_battling():
		return
	if get_tree().get_node_count_in_group("enemy_units") == 0:
		game_state.state = GameState.State.PREPARATION
		player_won.emit()
	if get_tree().get_node_count_in_group("player_units") == 0:
		game_state.state = GameState.State.PREPARATION
		enemy_won.emit()

# ===============================================

func _ready() -> void:
	game_state.changed.connect(
		func():
			if game_state.is_battling():
				__prepare_fight()
			else:
				__clean_up_fight()
	)


func _input(event: InputEvent) -> void:
	if event.is_action_pressed("ui_accept"):
		get_tree().call_group("enemy_units", "queue_free")
